<template>
  <div class="game-container">
    <!-- 游戏列表页面 -->
    <div v-if="!currentGame" class="game-list">
      <div class="game-header">
        <h1 class="page-title">游戏中心</h1>
        <div class="category-tabs">
          <span
            v-for="(category, idx) in categories"
            :key="idx"
            :class="['category-tab', { active: activeCategory === category.value }]"
            @click="activeCategory = category.value"
          >
            {{ category.label }}
          </span>
        </div>
      </div>

      <div class="games-grid">
        <div
          v-for="(game, index) in filteredGames"
          :key="index"
          class="game-item"
          @click="startGame(game)"
          @mouseenter="hoverGame = index"
          @mouseleave="hoverGame = -1"
        >
          <div class="game-cover" :style="{ backgroundColor: getGameColor(game, true) }">
            <div class="game-icon">
              <component :is="getGameIcon(game)" :class="{ 'icon-hover': hoverGame === index }" />
            </div>
            <div class="game-overlay" :class="{ active: hoverGame === index }">
              <el-button round @click.stop="startGame(game)">开始游戏</el-button>
            </div>
            <div class="favorite-btn" @click.stop="toggleFavorite(game)">
              <component :is="FavoriteIcon" :active="isFavorite(game)" />
            </div>
          </div>
          <div class="game-details">
            <h3 class="game-name">
              {{ game.name }}
              <span v-if="isFavorite(game)" class="favorite-badge">★</span>
            </h3>
            <div class="game-type" :style="{ backgroundColor: getGameColor(game, true) }">
              {{ getGameType(game) }}
            </div>
          </div>
        </div>

        <!-- 收藏为空的提示 -->
        <div
          v-if="activeCategory === 'favorites' && filteredGames.length === 0"
          class="empty-favorites"
        >
          <i class="el-icon-star-off"></i>
          <p>暂无收藏游戏</p>
          <p class="empty-favorites-hint">点击游戏卡片右上角的星标添加收藏</p>
        </div>
      </div>
    </div>

    <!-- 游戏界面 -->
    <div v-else class="game-play-view">
      <div class="game-nav">
        <button class="back-button" @click="backToList">
          <i class="el-icon-arrow-left"></i>
          返回游戏列表
        </button>
        <h2 class="current-game-title">{{ currentGame.name }}</h2>
        <div class="game-actions">
          <el-button circle icon="el-icon-refresh"></el-button>
          <el-button circle icon="el-icon-full-screen"></el-button>
        </div>
      </div>
      <div class="game-frame-container">
        <iframe :src="currentGame.url" class="game-frame" frameborder="0" allowfullscreen></iframe>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { h } from "vue";
import { Star, StarFilled } from "@element-plus/icons-vue";
// 引入API
import { type GameCategory as GameCategoryType } from "@/api/game/gameInfo";

interface Game {
  id: number;
  name: string;
  url: string;
  description?: string;
  coverImage?: string;
  category?: string;
  categoryInfo?: GameCategoryType;
  rating?: number;
  developer?: string;
}

interface Category {
  label: string;
  value: string;
}

// 图标组件
const ShootingIcon = (
  props: { class?: string | Record<string, boolean> },
  { attrs }: { attrs: Record<string, any> }
) => {
  return h(
    "svg",
    {
      ...attrs,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      class: ["game-svg", props.class],
    },
    [
      h("path", {
        d: "M14 5l7 7m0 0l-7 7m7-7H3",
        "stroke-width": "2",
        "stroke-linecap": "round",
        "stroke-linejoin": "round",
      }),
    ]
  );
};

const RPGIcon = (
  props: { class?: string | Record<string, boolean> },
  { attrs }: { attrs: Record<string, any> }
) => {
  return h(
    "svg",
    {
      ...attrs,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      class: ["game-svg", props.class],
    },
    [
      h("path", {
        d: "M12 2L8 6h8l-4 4m0 14v-8m-8 4h16",
        "stroke-width": "2",
        "stroke-linecap": "round",
        "stroke-linejoin": "round",
      }),
    ]
  );
};

const StrategyIcon = (
  props: { class?: string | Record<string, boolean> },
  { attrs }: { attrs: Record<string, any> }
) => {
  return h(
    "svg",
    {
      ...attrs,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      class: ["game-svg", props.class],
    },
    [
      h("path", {
        d: "M8 2v4m8-4v4M3 10h18M7 21h10a2 2 0 002-2V10H5v9a2 2 0 002 2z",
        "stroke-width": "2",
        "stroke-linecap": "round",
        "stroke-linejoin": "round",
      }),
    ]
  );
};

const CasualIcon = (
  props: { class?: string | Record<string, boolean> },
  { attrs }: { attrs: Record<string, any> }
) => {
  return h(
    "svg",
    {
      ...attrs,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      class: ["game-svg", props.class],
    },
    [
      h("path", {
        d: "M12 6v6m0 0v6m0-6h6m-6 0H6",
        "stroke-width": "2",
        "stroke-linecap": "round",
        "stroke-linejoin": "round",
      }),
    ]
  );
};

const DefaultIcon = (
  props: { class?: string | Record<string, boolean> },
  { attrs }: { attrs: Record<string, any> }
) => {
  return h(
    "svg",
    {
      ...attrs,
      viewBox: "0 0 24 24",
      fill: "none",
      stroke: "currentColor",
      class: ["game-svg", props.class],
    },
    [
      h("circle", {
        cx: "12",
        cy: "12",
        r: "9",
        "stroke-width": "2",
      }),
      h("path", {
        d: "M9 12h6m-3-3v6",
        "stroke-width": "2",
        "stroke-linecap": "round",
      }),
    ]
  );
};

// 收藏图标组件
const FavoriteIcon = (props: { active?: boolean }) => {
  return h(props.active ? StarFilled : Star, {
    style: {
      width: "18px",
      height: "18px",
      color: props.active ? "#f1c40f" : "#606266",
    },
  });
};

// 当前状态
const currentGame = ref<Game | null>(null);
const hoverGame = ref(-1);
const activeCategory = ref("all");
const favoriteGames = ref<number[]>(JSON.parse(localStorage.getItem("favoriteGames") || "[]"));
const loading = ref(false);

// 游戏数据
const games = ref<Game[]>([]);
const systemCategories = ref<GameCategoryType[]>([]);

// 游戏分类
const categories = ref<Category[]>([
  { label: "全部游戏", value: "all" },
  { label: "我的收藏", value: "favorites" },
]);

// 填充游戏数据
const fillGameData = () => {
  const gameData = [
    {
      name: "七绝",
      url: "http://www.54yx.com/i/123/qj/",
      type: "角色扮演",
    },
    {
      name: "弹弹堂",
      url: "http://www.454yx.com/Server_List_477.html",
      type: "休闲",
    },
    {
      name: "无限纷争",
      url: "https://a.9game.cn/news/10795608.html",
      type: "格斗",
    },
    {
      name: "部落冲突",
      url: "https://www.4399.com/flash/203128.htm",
      type: "策略",
    },
    {
      name: "天才枪手",
      url: "https://a.9game.cn/news/10298360.html",
      type: "射击",
    },
    {
      name: "我是大英雄",
      url: "http://www.54yx.com/i/123/wsdyx/",
      type: "角色扮演",
    },
    {
      name: "模拟城市",
      url: "https://www.4399.com/flash/203128.htm",
      type: "模拟经营",
    },
    {
      name: "漫威超级争霸战",
      url: "https://a.9game.cn/news/10795608.html",
      type: "格斗",
    },
    {
      name: "UI设计规范测试器",
      url: "https://cantunsee.space",
      type: "解密",
    },
    {
      name: "刺客信条",
      url: "https://www.4399.com/flash/203128.htm",
      type: "动作冒险",
    },
    {
      name: "超级跑跑",
      url: "http://www.onlinedown.net/zt/758/index.html",
      type: "体育",
    },
    {
      name: "机械纪元",
      url: "http://www.63yy.com/i/123/770/",
      type: "角色扮演",
    },
    {
      name: "梦幻花园",
      url: "https://www.4399.com/flash/203128.htm",
      type: "休闲",
    },
    {
      name: "拳皇命运",
      url: "https://a.9game.cn/news/10795608.html",
      type: "格斗",
    },
    {
      name: "海岛奇兵",
      url: "https://www.4399.com/flash/203128.htm",
      type: "策略",
    },
    {
      name: "全民枪王",
      url: "https://a.9game.cn/news/10298360.html",
      type: "射击",
    },
    {
      name: "Parcel Corps",
      url: "https://news.17173.com/z/pd2024/content/11182024/093146222.shtml",
      type: "竞速",
    },
    {
      name: "仙侠神域返利版",
      url: "http://www.63yy.com/i/123/687/",
      type: "角色扮演",
    },
    {
      name: "开心农场",
      url: "https://www.4399.com/flash/203128.htm",
      type: "模拟经营",
    },
    {
      name: "暴力街区 2",
      url: "https://a.9game.cn/news/10795608.html",
      type: "格斗",
    },
    {
      name: "像素眼游戏",
      url: "https://www.pixact.ly/",
      type: "解密",
    },
    {
      name: "古墓丽影",
      url: "https://www.4399.com/flash/203128.htm",
      type: "动作冒险",
    },
    {
      name: "拍拍部落",
      url: "http://www.onlinedown.net/zt/758/index.html",
      type: "体育",
    },
    {
      name: "少年江山",
      url: "http://www.63yy.com/i/123/715/",
      type: "角色扮演",
    },
    {
      name: "开心消消乐",
      url: "https://www.4399.com/flash/203128.htm",
      type: "休闲",
    },
    {
      name: "地下城与勇士",
      url: "https://www.zhanww.com/a/zuixinwangyoudongtai/2023/1026/5147.html",
      type: "格斗",
    },
    {
      name: "率土之滨",
      url: "https://www.4399.com/flash/203128.htm",
      type: "策略",
    },
    {
      name: "高能英雄",
      url: "https://a.9game.cn/news/10298360.html",
      type: "射击",
    },
    {
      name: "#DRIVE Rally",
      url: "https://news.17173.com/z/pd2024/content/11182024/093146222.shtml",
      type: "竞速",
    },
    {
      name: "钢笔工具训练器",
      url: "https://bezier.method.ac",
      type: "解密",
    },
    {
      name: "大富翁",
      url: "https://www.4399.com/flash/203128.htm",
      type: "模拟经营",
    },
    {
      name: "神秘海域",
      url: "https://www.4399.com/flash/203128.htm",
      type: "动作冒险",
    },
    {
      name: "网球宝贝",
      url: "http://www.onlinedown.net/zt/758/index.html",
      type: "体育",
    },
    {
      name: "植物大战僵尸",
      url: "https://www.4399.com/flash/203128.htm",
      type: "休闲",
    },
    {
      name: "三国志战略版",
      url: "https://www.4399.com/flash/203128.htm",
      type: "策略",
    },
    {
      name: "小小突击队",
      url: "https://a.9game.cn/news/10298360.html",
      type: "射击",
    },
    {
      name: "疯狂坦克",
      url: "https://news.17173.com/z/pd2024/content/11182024/093146222.shtml",
      type: "竞速",
    },
    {
      name: "曲线造字游戏",
      url: "https://shape.method.ac",
      type: "解密",
    },
    {
      name: "动物园大亨",
      url: "https://www.4399.com/flash/203128.htm",
      type: "模拟经营",
    },
    {
      name: "生化危机",
      url: "https://www.4399.com/flash/203128.htm",
      type: "动作冒险",
    },
    {
      name: "全民足球",
      url: "http://www.onlinedown.net/zt/758/index.html",
      type: "体育",
    },
    {
      name: "愤怒的小鸟",
      url: "https://www.4399.com/flash/203128.htm",
      type: "休闲",
    },
    {
      name: "皇室战争",
      url: "https://www.4399.com/flash/203128.htm",
      type: "策略",
    },
    {
      name: "生死狙击2",
      url: "https://www.4399.com/",
      type: "射击",
    },
    {
      name: "一鹅当先",
      url: "https://news.17173.com/z/pd2024/content/11182024/093146222.shtml",
      type: "竞速",
    },
    {
      name: "字间距游戏",
      url: "https://type.method.ac",
      type: "解密",
    },
    {
      name: "过山车大亨",
      url: "https://www.4399.com/flash/203128.htm",
      type: "模拟经营",
    },
    {
      name: "战神",
      url: "https://www.4399.com/flash/203128.htm",
      type: "动作冒险",
    },
    {
      name: "自由足球",
      url: "http://www.onlinedown.net/zt/758/index.html",
      type: "体育",
    },
    {
      name: "王牌竞速",
      url: "https://news.17173.com/z/pd2024/content/11182024/093146222.shtml",
      type: "竞速",
    },
  ];

  // 创建一个所有游戏类型的集合
  const gameTypes = [...new Set(gameData.map((game) => game.type))];

  // 更新分类选项
  systemCategories.value = gameTypes.map((type, index) => ({
    id: index + 1,
    name: type,
    code: type.toLowerCase(),
  }));

  // 更新游戏数据
  games.value = gameData.map((game, index) => ({
    id: index + 1,
    name: game.name,
    url: game.url,
    description: `这是${game.name}游戏的描述。`,
    coverImage: "",
    category: game.type.toLowerCase(),
    categoryInfo: {
      id: systemCategories.value.find((cat) => cat.name === game.type)?.id || 0,
      name: game.type,
      code: game.type.toLowerCase(),
    },
    rating: Math.floor(Math.random() * 5) + 1,
    developer: "游戏开发商",
  }));

  // 更新分类列表，保留"全部"和"收藏"选项
  categories.value = [
    { label: "全部游戏", value: "all" },
    { label: "我的收藏", value: "favorites" },
    ...gameTypes.map((type, index) => ({
      label: type,
      value: (index + 1).toString(),
    })),
  ];
};

// 获取游戏列表
const fetchGames = async () => {
  loading.value = true;
  try {
    if (activeCategory.value === "all") {
      // 使用本地游戏数据
      fillGameData();
    } else if (activeCategory.value === "favorites") {
      // 收藏的游戏通过本地存储ID过滤
      fillGameData();
      games.value = games.value.filter((game) => favoriteGames.value.includes(game.id));
    } else {
      // 获取分类游戏
      fillGameData();
      const categoryId = parseInt(activeCategory.value);
      games.value = games.value.filter((game) => game.categoryInfo?.id === categoryId);
    }
  } catch (error) {
    console.error("获取游戏列表失败:", error);
    ElMessage.error("获取游戏列表失败");
  } finally {
    loading.value = false;
  }
};

// 根据分类筛选游戏
const filteredGames = computed(() => {
  // 收藏的游戏排在前面
  if (activeCategory.value !== "favorites") {
    return games.value.sort((a, b) => {
      const aIsFavorite = favoriteGames.value.includes(a.id);
      const bIsFavorite = favoriteGames.value.includes(b.id);

      if (aIsFavorite && !bIsFavorite) {
        return -1; // a排在前面
      } else if (!aIsFavorite && bIsFavorite) {
        return 1; // b排在前面
      }
      return 0; // 保持原有顺序
    });
  }
  return games.value;
});

// 获取游戏类型名称
const getGameType = (game: Game): string => {
  if (game.categoryInfo) {
    return game.categoryInfo.name;
  }

  if (game.category) {
    const category = systemCategories.value.find((c) => c.code === game.category);
    if (category) {
      return category.name;
    }
  }

  return "其他游戏";
};

// 获取游戏图标组件
const getGameIcon = (game: Game): any => {
  const category = game.category || "";

  if (category.includes("shooting") || category.includes("action")) {
    return ShootingIcon;
  }
  if (category.includes("rpg") || category.includes("adventure")) {
    return RPGIcon;
  }
  if (category.includes("strategy")) {
    return StrategyIcon;
  }
  if (category.includes("casual") || category.includes("puzzle")) {
    return CasualIcon;
  }

  return DefaultIcon;
};

// 根据游戏名称获取颜色
const getGameColor = (game: Game, isLight = false): string => {
  const category = game.category || "";

  if (category.includes("shooting") || category.includes("action")) {
    return isLight ? "rgba(231, 76, 60, 0.1)" : "#e74c3c";
  }
  if (category.includes("rpg") || category.includes("adventure")) {
    return isLight ? "rgba(52, 152, 219, 0.1)" : "#3498db";
  }
  if (category.includes("strategy")) {
    return isLight ? "rgba(243, 156, 18, 0.1)" : "#f39c12";
  }
  if (category.includes("casual") || category.includes("puzzle")) {
    return isLight ? "rgba(155, 89, 182, 0.1)" : "#9b59b6";
  }

  return isLight ? "rgba(46, 204, 113, 0.1)" : "#2ecc71";
};

// 开始游戏
const startGame = async (game: Game) => {
  try {
    loading.value = true;

    // 直接使用传入的游戏数据，不再调用API
    currentGame.value = {
      ...game,
      description: `这是${game.name}游戏的描述。`,
      developer: "游戏开发商",
    };

    ElMessage.success(`正在加载游戏：${game.name}`);
  } catch (error) {
    console.error("加载游戏失败:", error);
    ElMessage.error("加载游戏失败");
  } finally {
    loading.value = false;
  }
};

// 返回游戏列表
const backToList = () => {
  currentGame.value = null;
};

// 收藏游戏
const toggleFavorite = (game: Game) => {
  const index = favoriteGames.value.findIndex((id) => id === game.id);
  if (index === -1) {
    // 添加收藏
    favoriteGames.value.push(game.id);
    ElMessage.success(`已将"${game.name}"添加到收藏`);
  } else {
    // 取消收藏
    favoriteGames.value.splice(index, 1);
    ElMessage.success(`已将"${game.name}"从收藏中移除`);
  }
  // 保存到本地存储
  localStorage.setItem("favoriteGames", JSON.stringify(favoriteGames.value));

  // 如果在收藏页面取消收藏，需要刷新列表
  if (activeCategory.value === "favorites") {
    fetchGames();
  }
};

// 判断游戏是否已收藏
const isFavorite = (game: Game) => {
  return favoriteGames.value.includes(game.id);
};

// 监听分类变化
watch(activeCategory, () => {
  fetchGames();
});

onMounted(() => {
  fillGameData();
  fetchGames();
});
</script>

<style scoped>
.game-container {
  width: 100%;
  min-height: 100vh;
  background-color: #f8f9fa;
  padding: 0;
  overflow: hidden;
}

/* 游戏列表页面样式 */
.game-list {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.game-header {
  margin-bottom: 30px;
  display: flex;
  flex-direction: column;
}

.page-title {
  margin: 0 0 20px 0;
  font-size: 32px;
  font-weight: 700;
  color: #333;
}

.category-tabs {
  display: flex;
  gap: 16px;
  margin-bottom: 20px;
  border-bottom: 1px solid #eaeaea;
  padding-bottom: 10px;
}

.category-tab {
  padding: 8px 16px;
  cursor: pointer;
  font-size: 15px;
  border-radius: 20px;
  transition: all 0.3s ease;
  color: #666;
}

.category-tab:hover {
  background-color: #f1f1f1;
  color: #333;
}

.category-tab.active {
  background-color: #333;
  color: white;
  font-weight: 500;
}

.games-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  gap: 24px;
}

.game-item {
  background: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 6px 16px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
  cursor: pointer;
}

.game-item:hover {
  transform: translateY(-8px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.game-cover {
  position: relative;
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  overflow: hidden;
}

.game-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
  height: 100%;
  transition: all 0.4s ease;
}

.game-svg {
  width: 60px;
  height: 60px;
  stroke: white;
  stroke-width: 1.5;
  transition: all 0.4s ease;
}

.icon-hover {
  transform: scale(1.2);
}

.game-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: all 0.3s ease;
}

.game-overlay.active {
  opacity: 1;
}

.game-details {
  padding: 16px;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.game-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  display: flex;
  align-items: center;
}

.favorite-badge {
  font-size: 12px;
  color: #f1c40f;
  margin-left: 6px;
}

.game-type {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  color: #666;
  align-self: flex-start;
}

/* 游戏播放页面样式 */
.game-play-view {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.game-nav {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 24px;
  background: #fff;
  border-bottom: 1px solid #eaeaea;
}

.back-button {
  display: flex;
  align-items: center;
  gap: 8px;
  background: none;
  border: none;
  cursor: pointer;
  font-size: 14px;
  color: #666;
  transition: color 0.3s ease;
  padding: 8px 16px;
  border-radius: 4px;
}

.back-button:hover {
  background-color: #f1f1f1;
  color: #333;
}

.current-game-title {
  font-size: 18px;
  font-weight: 600;
  margin: 0;
  color: #333;
}

.game-actions {
  display: flex;
  gap: 8px;
}

.game-frame-container {
  flex-grow: 1;
  display: flex;
  overflow: hidden;
}

.game-frame {
  flex-grow: 1;
  border: none;
  width: 100%;
  height: 100%;
}

.favorite-btn {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  z-index: 10;
  transition: all 0.3s ease;
}

.favorite-btn:hover {
  transform: scale(1.1);
  background: white;
}

.empty-favorites {
  grid-column: 1 / -1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  background-color: #f9f9f9;
  border-radius: 12px;
  color: #909399;
}

.empty-favorites i {
  font-size: 48px;
  margin-bottom: 16px;
}

.empty-favorites p {
  margin: 4px 0;
  font-size: 16px;
}

.empty-favorites-hint {
  font-size: 14px;
  opacity: 0.7;
}
</style>
